/**
 * @author yuntao zhou
 * require core_1.1.js
 */
//subtype 14_6
if(!QSAPI){
	var QSAPI={};
}

if(!QSAPI.Widget){
	QSAPI.Widget={};
}

QSAPI.Widget.MarketCommodityFutures = function(container,config,callback,id){
	/*removed the image icons, instead of background icons*/
	/**
     * @GC  @GC0Y  Comex Gold       66.3.@GC0Y
     * @CL  @CL0Y  Sweet Crude Oil  67.3.@CL0Y
     * @NG  @NG0Y  Natural Gas      67.3.@NG0Y
     */   
	this.container=container;
	this.config={
		accuracy:2,
		showYear:true,
		lang:typeof QS_Lang!='undefined'&& typeof QS_Lang.commodityfutures!='undefined'?QS_Lang.commodityfutures:{}
	}
	
	if(config){
		$.extend(this.config,config);
	}
	
	this.callback={};
	if(callback){
		$.extend(this.callback,callback);
	}
	
	this.subscribeID=this.id=id;// DataManager need subsribeID.
	
    //this.profile = {}
    this.HTML = '<div class="qs_marketcommodityfutures clearfix"></div>';    
    this.moduleHTML = '<div class="module">'+
               '<div class="pic"></div>'+
               '<h5 class="sector row">sector</h5>'+
              // '<div class="symbol row">symbol</div>'+
               '<div class="LastPrice row">LastPrice</div>'+
               '<div class="Chg row">Chg%</div>'+
               '<div class="Chgper row" style="text-indent:60px;">Chg%</div>'+
               '<div class="Date row">Date</div>'+
           '</div>';
           
    
    //this.symbols = ['/66:@GC1J','/67:@CL1K','/67:@NG1K'];
	
	
//    this.validSymbolsReady = false;
//    this.validSymbols = [];
//    this.symbolsNameMap ={
//       '66:@GC1J':"Comex Gold",'67:@CL1K':"Sweet Crude Oil",'67:@NG1K':"Natural Gas"
//    }

//	var module = QS_Lang.commodityfutures;

    this.symbolsNameMap ={
       '66:@GC':this.config.lang['gold'],
	   '67:@CL':this.config.lang['oil'],
	   '67:@NG':this.config.lang['gas']
    }
	
//    if (typeof QS_FuturesMap == 'undefined') {
//        QS_FuturesMap = {};
//    }
      
      
    //this.dMap = {0:'Sunday', 1:"Monday", 2:"Tuesday", 3:"Wednesday", 4:"Thursday", 5:"Friday", 6:"Saturday"};
    //this.mMap = {0:'January', 1:"February", 2:"March", 3:"April", 4:"May", 5:"June", 6:"July", 7:"August", 8:"September", 9:"October", 10:"November", 11:"December"};
    this.symbolsDomMap = {};
    //this.tValidation = new tickerValidation(17);
	//this.SecIds = [];
	this.init();
}

QSAPI.Widget.MarketCommodityFutures .prototype = {
    init: function(){
		var self=this;
        //this.containerId = ContainerId;
        //this.container = $('#' + ContainerId);
        //this.id = Sid;
        //this.profile = Profile;
        this.el = $(this.HTML);
        this.el.appendTo(this.container);
        
//      this.scrollPanel = new Util.ScrollPanel(this.el);
		QSAPI.TickerFactory.create(['66.3.@GC0Y','67.3.@CL0Y','67.3.@NG0Y'],{
			onSuccess:function(tickerObjects){
				if(QSAPI.DataManager._getType()==QSAPI.DataManager.TYPE.PUSH){
					QSAPI.DataManager.subscribePush(self,tickerObjects,{
						onSuccess:function(result){
							self.buildModulesByTickerObject(result.tickerObjects);
						}
					},false)
				}else{
					QSAPI.DataManager.subscribePull(self,tickerObjects,{
						onSuccess:function(result){
							self.buildModulesByTickerObject(result.tickerObjects);
						}
					})
				}
			} 
		});       
    },
	buildModulesByTickerObject:function(tickerObjects){
		var gKeyList=[];
		for(var i=0,l=tickerObjects.length;i<l;i++){
			gKeyList.push(tickerObjects[i].getField('gkey'));
		}
		this.bindModules(gKeyList);
	},
	/*_getTickers: function(){
		var self = this;
		if (!window['QS_UserID']) {
			window['QS_UserID'] = 'QUEST';
		}
		DBHelper.getCommodity('Overview', function(data){
			if (data != null && data != '') {
				self.holdings = [];
				var jData = $.evalJSON(data);
				var symbols = jData.Overview, s, tickers = ['@GC', '@CL', '@NG'];
				for (var j = 0, len = tickers.length; j < len; j++) {
					s = symbols[tickers[j]];
					if (s) {
						var details = s.Details;
						var exch = s.Exch || '';
						var feedSrcId = s.FeedSrcId;
						
						for (var i = 0, l = details.length; i < l; i++) {
							symbol = details[i][0];
							if (symbol.substring(symbol.length - 1, symbol.length) != 'Y') {
								self.SecIds.push("/" + feedSrcId + ":" + symbol);
								break;
							}
						}
					}
				}
				if (self.SecIds.length > 0) {
					self._checkTickers();
				}
			}
		});
	},
    
    _checkTickers: function(){
        var self = this;
		
        this.tValidation.checkTickers(this.SecIds, function(validSymbols){
            self.validSymbolsReady = true;
            self.validSymbols = validSymbols;
            //callback.call(self);
            self.bindModules()
        });
    },*/
    
    bindModules: function(gKeyList){
 /*       if (this.validSymbolsReady == false) {
			this._getTickers();
            //this._checkTickers();
//          this.validSymbols = ['66:@GC1J','67:@CL1K','67:@NG1K'];
//          this.validSymbolsReady = true;
//          this.bindModules();
        }
        else {
            for (var idx = 0, l = this.config.tickers.length; idx < l; idx++) {
                this.bindModule(this.config.tickers[idx]);
            }
            this.changeOutSize();
        }
		*/
		for (var idx = 0, l = gKeyList.length; idx < l; idx++) {
			this.bindModule(gKeyList[idx]);
		}
		this.changeOutSize();
    },
    
    bindModule: function(gKey, el){
        var el = $(this.moduleHTML);
        var imgObj = el.find('.pic');
		/*removed the image icons, instead of background icons*/
        switch (gKey.substr(0,6)) {
            case '66:@GC':{
				imgObj.addClass("gold");
                //imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_gold.png" />');
            }break;
            case '67:@CL':{
				imgObj.addClass("crude");
                //imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_crude.png" />');
            }break;
            case '67:@NG':{
				imgObj.addClass("natgas");
                //imgObj.html('<img src="//rtqimg.morningstar.com/theme/'+QS_Theme+'/ico_natgas.png" />');
            }break;
        }
        this._flashModule(gKey, el);
        if (!this.symbolsDomMap[gKey]) 
            this.symbolsDomMap[gKey] = el;
        el.appendTo(this.el);
    },
    
    _flashModule: function(gKey, el){
        el.find(".sector").html(this.symbolsNameMap[gKey.substr(0,6)]);
        this._flashField(gKey, 'Date', el);
        this._flashField(gKey, 'LastPrice', el);
        this._flashField(gKey, 'Chg', el);
        this._flashField(gKey, 'Chg%', el);
    },
    
    _flashField: function(gKey, field, el){
        var value = 0.00;
        if (typeof(gData[gKey]) != 'undefined' && typeof(gData[gKey][field]) != 'undefined') {
            value = gData[gKey][field];
        }
        if (field == 'Date') {
			var d = null;
			if (!/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(value)) {
				d = new Date();
			}
			else {//YYYY-MM-DD
				var t = value.split("-");
				d = new Date(t[0], parseInt(t[1]) - 1, t[2]);
			}
			//value = this.dMap[d.getDay()] + ',' + this.mMap[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
			//value = this.mMap[d.getMonth()] + ' ' + d.getDate() + (this.config.showYear === false ? '' : (', ' + d.getFullYear()));
			value=QS_DateFmt.getDateString(d);
			el.find(".Date")[0]['innerHTML'] = value;
		}
		else {
			this._updateFieldDom(field, el.find("." + (field == "Chg%" ? "Chgper" : field))[0], value, value, true);
		}
    },
    
    _updateFieldDom: function(field, el, data, oldValue, needFlash){
        var _flashMethod = needFlash === false ? (function(){}) : Util.flash;
        switch (field) {
            case 'LastPrice':
                _flashMethod(el, data, oldValue);
				data = QS_NumFmt.Fmt2(data,false,"",this.config.accuracy); //data.toFixed(accuracy);
                //data = Util.formatDoubledata(data, "future");
				//el.style.color = data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
                el['innerHTML'] = '<span>$'+data+'</span>';
                break;
            case 'Chg':
            case 'Chg%':
                if (needFlash !== false) {
                    Util.flashWithDirectional(el, data, oldValue, data >= 0);
                }
                else {
                    el.style.color = data >= 0 ? QS_Style.greenFontColor : QS_Style.redFontColor;
                }
				data = QS_NumFmt.Fmt2(data,false,"",this.config.accuracy); //data.toFixed(accuracy);
                //data = Util.formatDoubledata(data, "future");
				
				if (field == "Chg%") { // update the up/down column;
					var upd = data;
					if (upd == 0 || typeof upd == 'undefined') {
						upd = 'up';
					}
					else {
						upd = upd >= 0 ? "up" : "down";
					}
					
					var className = el.previousSibling.previousSibling.className, temp = className.match(/down$|up$/);
					if (temp != null && temp.length) {
						className = className.replace(/down$|up$/, upd);
					}
					else {
						className = className.replace(/$/, " " + upd);
					}
					el.previousSibling.previousSibling.className = className;
				}
				
                if(field=="Chg%")data=data+"%";
                el['innerHTML'] = data;
                break;
            default:
                break;
        }
    },
    
    updateData: function(tickerObject, aData, needFlash){
		var gKey=tickerObject.getField('gkey');
        if (gKey&&this.symbolsDomMap[gKey]) {
            for (var field in aData) {
                var el = this.symbolsDomMap[gKey].find('.' + (field == "Chg%" ? "Chgper" : field))[0];
                var data = aData[field].value;
                var oldValue = aData[field].oValue;
                this._updateFieldDom(field, el, data, oldValue, needFlash);
            }
        }
    },
    
    changeOutSize: function(w, h){
        w = w || this.config.width;
        h = h || this.config.height;
        
//        this.scrollPanel.reSize(w, h);
    },
	
	clear:function(){
		QSAPI.DataManager.deregisterComponent(this);
		for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
       }
	}
}